﻿using EasyModbus;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ModbusMasterDemo
{
    public partial class FormMain : Form
    {
        private ModbusClient _modbusClient;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {

        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string IP = this.txtIP.Text;
            int Port = (int)numPort.Value;
            _modbusClient = new ModbusClient(IP, Port);
            _modbusClient.Connect();

            if (_modbusClient.Connected)
            {
                this.btnConnect.Enabled = false;
                this.btnDisconnect.Enabled = true;
                this.panelWork.Enabled = true;
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            if (_modbusClient != null)
            {
                try
                {
                    _modbusClient.Disconnect();

                    this.btnConnect.Enabled = true;
                    this.btnDisconnect.Enabled = false;
                    this.panelWork.Enabled = false;
                }
                finally
                {
                    _modbusClient = null;
                }
            }
        }

        private void btnWrite_Click(object sender, EventArgs e)
        {
            int StartAddr = (int)this.numWriteAddr.Value;
            int Value = (int)this.numWriteValue.Value;
            _modbusClient.WriteSingleRegister(StartAddr, Value);
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            int StartAddr = (int)this.numReadAddr.Value;
            int[] words = _modbusClient.ReadHoldingRegisters(StartAddr, 1);
            this.txtReadValue.Text = words[0].ToString();
        }
    }
}
